import { createRouter, createWebHashHistory } from "vue-router";
import BaseLayout from "@/layout/index.vue";
import { RedirctRoute } from "./base";

/**modules */

/**
 * 排序
 * @param {import('vue-router').RouteRecord} a
 * @param {import('vue-router').RouteRecord} b
 * @returns
 */
function sortRoute(a, b) {
  return (a.meta?.sort || 0) - (b.meta?.sort || 0);
}

const modules = import.meta.globEager("./modules/**/*.js");

/**
 * @type {import('vue-router').RouteRecord[]}
 */
const routeModuleList = [];

Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

routeModuleList.sort(sortRoute);

export const asyncRoutes = [...routeModuleList];

export const constantRouter = [
  {
    path: "/",
    name: "base",
    component: BaseLayout,
    redirect: { name: "home" },
    meta: {
      title: "首页",
    },
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("@/views/Home.vue"),
        meta: {
          title: "首页",
        },
      },
      {
        path: "/test",
        name: "test",
        component: () => import("@/views/TestView.vue"),
        meta: {
          title: "test",
        },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue"),
    meta: {
      title: "登录",
    },
  },
  RedirctRoute,
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: constantRouter,
});

export default router;
